package com.wisedu.mobile.core.security;

import com.wisedu.mobile.common.AjaxResult;
import com.wisedu.mobile.common.constant.Constants;
import com.wisedu.mobile.common.constant.HttpStatus;
import com.wisedu.mobile.common.domain.LoginUser;
import com.wisedu.mobile.common.service.LogService;
import com.wisedu.mobile.common.service.TokenService;
import com.wisedu.mobile.common.utils.ServletUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author hj
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    LogService logService;
    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null)
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            final String ip = Lang.getIP(ServletUtils.getRequest());
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            logService.recordLogininfor(userName, Constants.LOGOUT, "退出成功",ip,os,browser);
        }
        ServletUtils.renderString(response, Json.toJson(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
    }
}
